package world.ztomorrow.user.utils;

import lombok.experimental.UtilityClass;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.Random;

@UtilityClass
public class ImgVerifyCodeUtils {

    // 随机验证码的字符范围
    private final String randomScope = "0123456789";
    // 随机数对象
    private final Random random = new Random();

    private final int width = 100;
    private final int height = 38;

    // 生成验证码
    public String generateVerifyCode(int len) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < len; i++) {
            sb.append(randomScope.charAt(random.nextInt(randomScope.length())));
        }
        return sb.toString();
    }

    // 绘制验证码
    public String getVerifyCodeImage(String code) throws IOException {
        BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics graphics = bufferedImage.getGraphics();
        graphics.setColor(new Color(204, 204, 204));
        graphics.fillRect(0, 0, width, height);

        // 绘制随机字符
        drawString(graphics, code);
        graphics.dispose();

        //将图片转换成Base64字符串
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        ImageIO.write(bufferedImage, "JPEG", stream);
        return Base64.getEncoder().encodeToString(stream.toByteArray());
    }

    // 绘制字符串
    private void drawString(Graphics g, String verifyCode) {
        for (int i = 1; i <= verifyCode.length(); i++) {
            g.setFont(new Font("Fixed", Font.PLAIN, 23));
            g.setColor(new Color(random.nextInt(101), random.nextInt(111), random
                    .nextInt(121)));
            g.translate(random.nextInt(3), random.nextInt(4));
            g.drawString(String.valueOf(verifyCode.charAt(i - 1)), 12 * i, 23);
        }
    }
}
